<script setup>
import headers from '~/src/components/headers.vue';
import {
    getArticleTypeAPI,
    uploadImgAPI,
    uploadArticleAPI,
    getSaveArticleAPI,
} from '@/apis/publish'
import { ref, shallowRef, onBeforeUnmount, onMounted } from 'vue';
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import useDataStore from '~/src/store';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';

defineOptions({
    name: 'Publish'
})

const router = useRouter()

const dataStore = useDataStore()
const { userInfo, isMobile } = storeToRefs(dataStore)

const UPLOAD_URL = import.meta.env.VITE_UPLOAD_URL

let typeList = ref([])  //笔记类型列表
let typeSelected = ref()    //选中的笔记类型
let imageUrl = ref()    // 预览图片（base64）
let imgFile = ref()     // 将要真实上传的图片
let title = ref()   // 笔记标题
let intro = ref()   // 笔记摘要

let insertId = ref()    // 上传到预览表的图片的id

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
let valueHtml = ref()
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

onMounted(() => {
    getSaveArticle()
})

/* -------------------------------- 获取上次保存的内容 ------------------------------- */
const getSaveArticle = async () => {
    let res = await getSaveArticleAPI(userInfo.value.user_id)
    if (res.code === 200) {
        ElMessage({
            message: '已成功加载上次保存的笔记',
            type: 'success'
        })
        title.value = res.data[0].article_title
        intro.value = res.data[0].article_introduction
        typeSelected.value = res.data[0].article_type * 1
        imageUrl.value = res.data[0].article_coverimg
        valueHtml.value = res.data[0].article_content
    }
}

/* ------------------------------- 请求笔记所有种类信息 ------------------------------- */
const getArticleType = async () => {
    let { data } = await getArticleTypeAPI()
    typeList.value = data
}
getArticleType()

/* ---------------------------------- 文件预览 ---------------------------------- */
/**
 * 选择文件后先自动上传到预览表，再从预览表中请求这个文件，预览为缩略图
 */
const beforeUpload = async (file) => {
    imgFile.value = file
    let reader = new FileReader()
    // 以base64格式读取
    reader.readAsDataURL(file)
    reader.onload = (e) => {
        imageUrl.value = e.target.result
    }
}
const uploadSuccess = (response) => {
    // console.log('response', response);
    insertId.value = response.data.insertId

}


/* -------------------------------- 创建富文本编辑器 -------------------------------- */
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor
}

/* -------------------------------- 点击保存/发布笔记按钮 -------------------------------- */
const publishAction = async (type) => {
    // 笔记信息对象
    let article = {
        title: title.value,     // 笔记标题
        intro: intro.value,     // 笔记摘要
        typeSelected: typeSelected.value,       // 笔记类型
        valueHtml: valueHtml.value,      // 笔记正文
        imgUrl: insertId.value ? '' : imageUrl.value
    }
    if (type === 'publish') {
        if (!article.title) return ElMessage({ message: "笔记标题不能为空" })
        if (!article.intro) return ElMessage({ message: "笔记描述不能为空" })
        if (!article.typeSelected) return ElMessage({ message: "笔记类型不能为空" })
        if (!imageUrl.value) return ElMessage({ message: "笔记封面不能为空" })
        if (!article.valueHtml) return ElMessage({ message: "笔记内容不能为空" })
    }

    ElMessageBox.confirm(
        type === 'publish' ? '笔记即将送往审核，通过后即可展示' : '笔记即将保存，下次可继续打开未完成的内容',
        '提示！！',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 用户信息对象
        let user = userInfo
        let { data } = await uploadArticleAPI(article, user.value, type, insertId.value)
        if (data) {
            ElMessage({
                message: type === 'publish' ? '上传笔记成功，正在等待审核' : '保存草稿成功',
                type: 'success'
            })
            router.push({ name: 'home' })

        }
    })
}

</script>

<template>
    <div class="page">
        <div class="container">
            <!-- <div class="headers">
                <headers :userInfo="userInfo"></headers>
            </div> -->
            <div class="temp" v-show="!isMobile"></div>
            <div class="main">
                <div class="main-title">发布笔记</div>
                <form class="main-article">
                    <div class="main-text">笔记标题</div>
                    <div class="article-title">
                        <el-input size="large" v-model="title" placeholder="在这里输入标题，30个字以内" maxlength="30"
                            show-word-limit />
                    </div>
                    <div class="second">
                        <div class="second-intro">
                            <div class="main-text">笔记摘要</div>
                            <div class="article-title">
                                <el-input type="textarea" rows="4" v-model="intro" placeholder="在这里输入摘要" />
                            </div>
                        </div>
                        <div class="second-select">
                            <div class="main-text">笔记类型</div>
                            <div class="select">
                                <el-select v-model="typeSelected" class="m-2" placeholder="请选择笔记类型" size="large"
                                    style="width: 240px">
                                    <el-option v-for="item in typeList" :key="item.type_id" :label="item.type_name"
                                        :value="item.type_id" />
                                </el-select>
                            </div>
                            <div class="main-text" style="text-align: end;">上传封面</div>
                        </div>
                        <div class="second-cover">
                            <el-upload class="avatar-uploader" :show-file-list="false" :action="UPLOAD_URL"
                                :before-upload="beforeUpload" :on-success="uploadSuccess">
                                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </div>
                    </div>

                    <div class="main-text">笔记内容</div>
                    <div id="editor—wrapper1">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                    <div class="main-send">
                        <el-button size="large" color="#626aef" @click="publishAction('publish')">发布笔记</el-button>
                        <el-button plain size="large" color="#626aef" @click="publishAction('save')">保存草稿</el-button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<style scoped lang='scss'>
@import url(./publish.scss);
</style>